package com.coisshi.base.module.captcha.utils;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.coisshi.base.framework.config.properties.CaptchaProperties;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.coisshi.base.common.constants.CacheKeyConstants.CAPTCHA;

/**
 * 验证码工具类（基于 Hutool + Redis）
 */
@Component
@RequiredArgsConstructor
public class CaptchaTool {

    private final CaptchaProperties captchaProperties;
    private final StringRedisTemplate redisTemplate;

    @Getter
    public static class CaptchaInfo {
        private final String codeId;
        private final String base64;

        public CaptchaInfo(String codeId, String base64) {
            this.codeId = codeId;
            this.base64 = base64;
        }
    }

    /**
     * 生成验证码图片（base64 + codeId）
     */
    public CaptchaInfo generateCaptcha() {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(
                captchaProperties.getWidth(),
                captchaProperties.getHeight(),
                captchaProperties.getLength(),
                captchaProperties.getLineCount()
        );

        String code = lineCaptcha.getCode();
        String base64 = lineCaptcha.getImageBase64Data();
        String codeId = IdUtil.fastSimpleUUID();

        String redisKey = buildKey(codeId);
        redisTemplate.opsForValue().set(redisKey, code, captchaProperties.getExpireSeconds(), TimeUnit.SECONDS);

        return new CaptchaInfo(codeId, base64);
    }

    /**
     * 校验验证码（匹配后立即清除）
     */
    public boolean validate(String codeId, String inputCode) {
        String redisKey = buildKey(codeId);
        String realCode = redisTemplate.opsForValue().get(redisKey);
        redisTemplate.delete(redisKey); // 无论成败都删除
        return realCode != null && realCode.equalsIgnoreCase(inputCode);
    }

    private String buildKey(String codeId) {
        return CAPTCHA + codeId;
    }
} 